package com.mrs.gauss.service.impl;

import com.mrs.gauss.common.ErrorCode;
import com.mrs.gauss.constant.UserConstant;
import com.mrs.gauss.exception.BusinessException;
import com.mrs.gauss.model.entity.MrsUser;
import com.mrs.gauss.model.vo.UserVO;
import com.mrs.gauss.service.dao.MrsUserDao;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.mrs.gauss.constant.UserConstant.USER_LOGIN_STATE;

/**
 * Created by hecq on 2024-12-24.
 *
 * @author hecq
 * @version 0.0.1
 * @date 2024-12-24
 * @since 0.0.1
 */
@Service
@Slf4j
public class MrsUserService {
    @Resource
    private MrsUserDao mrsUserDao;
    @Resource
    private MrsUserService userService;
    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "hecq";

    public int addUser(String userAccount,String userPassword, String checkPassword, String planetCode) {

        // 1. 校验
        //  校验非空使用**apache commons lang** 这个依赖
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, planetCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
//            return -1;
        }
        if (userAccount.length() < 3) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号小于3位");
//            return -1;
        }

        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码至少8位");
//            return -1;
        }
        if (planetCode.length() > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "集群账号过长！");
//            return -1;
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return -1;
        }
        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            return -1;
        }
        // 2. 加密 spring boot一个加密工具
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 3. 插入数据
        MrsUser user = new MrsUser();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setPlanetCode(planetCode);
        // 账户不能重复
        MrsUser userAcc = mrsUserDao.getUserAcc(userAccount);

        if (userAcc!=null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "此账号已被注册");
//            return -1;
        }
        // 集群账号不能重复
        MrsUser planetCo = mrsUserDao.getUserPlanetCo(planetCode);
        if (planetCo!=null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "集群账号重复");
//            return -1;
        }
        return mrsUserDao.add(user);
    }
    /**
     * 用户登录
     *
     * @param userAccount  用户账户
     * @param userPassword 用户密码
     * @param request
     * @return 脱敏后的用户信息
     */

    public MrsUser userLogin(String userAccount, String userPassword, HttpServletRequest request) {

        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码账号为空");
        }
        if (userAccount.length() < 3) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
//            return null;
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return null;
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 查询用户是否存在
        MrsUser user = mrsUserDao.getUserListOne(userAccount,encryptPassword);
        // 用户不存在
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "登录失败 账号或密码错误");
        }
        // 3. 用户脱敏
        MrsUser safetyUser = getSafetyUser(user);
        // 4. 记录用户的登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, safetyUser);
        return safetyUser;
    }

    public int updateUser(MrsUser user,String userAccount,String userPassword,  String planetCode,String planet,Integer userRole,String email,HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        MrsUser currentUser = (MrsUser) userObj;
        if (!userService.isAdmin(request) && !userAccount.equals(currentUser.getUserAccount()) ) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "缺少管理员权限 仅限修改当前登录用户");
        }
        if (!userService.isAdmin(request) ) {
            userRole = 0;
        }
        // 1. 校验
        //  校验非空使用**apache commons lang** 这个依赖
        if (StringUtils.isAnyBlank(userAccount)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号参数为空");
//            return -1;
        }
        if (userAccount.length() < 3) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号小于3位");
//            return -1;
        }

        if (userPassword.length() < 8 ){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码至少8位");
//            return -1;
        }
        if (planetCode.length() > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "集群账号过长！");
//            return -1;
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return -1;
        }
        // 不能修改账号
        MrsUser userAcc = mrsUserDao.getUserAcc(userAccount);

        if (userAcc == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "不能修改账号名");
//            return -1;
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setPlanetCode(planetCode);
        user.setPlanet(planet);
        user.setUserRole(userRole);
        user.setEmail(email);
        return mrsUserDao.update(user);
    }
    public List<MrsUser> getUserList() {
        return mrsUserDao.getUserList();
    }
    public long deleteUser(Long userId,HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "缺少管理员权限");
        }
        return mrsUserDao.delete(userId);
    }

    /**
     *
     * 用户脱敏
     *
     * @param originUser
     * @return
     */

    public MrsUser getSafetyUser(MrsUser originUser) {
        if (originUser == null) {
            return null;
        }
        MrsUser safetyUser = new MrsUser();
        safetyUser.setId(originUser.getId());
        safetyUser.setUserAccount(originUser.getUserAccount());
        safetyUser.setUserPassword("********");
        safetyUser.setPlanet(originUser.getPlanet());
        safetyUser.setEmail(originUser.getEmail());
        safetyUser.setUserStatus(originUser.getUserStatus());
        safetyUser.setCreateTime(originUser.getCreateTime());
        safetyUser.setUpdateTime(originUser.getUpdateTime());
        safetyUser.setIsDelete(originUser.getIsDelete());
        safetyUser.setUserRole(originUser.getUserRole());
        safetyUser.setPlanetCode(originUser.getPlanetCode());
        return safetyUser;
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */

    public MrsUser getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        MrsUser currentUser = (MrsUser) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 从数据库查询（追求性能的话可以注释，直接走缓存）
        String userAccount = currentUser.getUserAccount();
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + currentUser.getUserPassword()).getBytes());
        currentUser = mrsUserDao.getUserListOne(userAccount,encryptPassword);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;

    }
    /**
     * 用户注销
     *
     * @param request
     */
    public int userLogout(HttpServletRequest request) {
        // 移除登录态
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return 1;
    }


    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    public boolean isAdmin(HttpServletRequest request) {
        // 需登录且仅管理员可查询
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        MrsUser user = (MrsUser) userObj;
        return user != null && user.getUserRole() == UserConstant.ADMIN_ROLE;
    }

    public UserVO getUserVO(MrsUser user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }
}
